package com.cn.activeMQ;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

import javax.jms.*;

/**
 * @program: demo
 * @description: 订阅模式  持久化
 * @author: yihanyuan
 * @create: 2019-08-28 15:07
 */
public class ActiveMqTest2 {
    @Test
    public void send() throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
//        connection.setClientID("client-1");
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic("topic");
        MessageProducer producer = session.createProducer(topic);
        TextMessage message = session.createTextMessage("message1");
        producer.send(message, DeliveryMode.PERSISTENT, 1, 1000 * 60 * 60 * 24);
        producer.close();
        session.close();
        connection.close();
    }

    @Test
    public void accept() throws JMSException, InterruptedException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
        //设置客户端id
        connection.setClientID("client-1");
        connection.start();
//        .AUTO_ACKNOWLEDGE 自动应答        CLIENT_ACKNOWLEDGE  手动应答
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic("topic");
        TopicSubscriber consumer = session.createDurableSubscriber(topic, "clint1-sub");
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    String text = ((TextMessage) message).getText();
                    System.out.println(((TextMessage) message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread.sleep(100000);
    }
}
